package com.li.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.li.blog.dao.mapper.SysUserMapper;
import com.li.blog.dao.pojo.SysUser;
import com.li.blog.service.LoginService;
import com.li.blog.service.SysUserService;
import com.li.blog.vo.ErrorCode;
import com.li.blog.vo.LoginUserVo;
import com.li.blog.vo.Result;
import com.li.blog.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SysUserImpl implements SysUserService {

  @Autowired
  private SysUserMapper sysUserMapper;
  @Autowired
  private LoginService loginService;

  @Override
  public SysUser findUserById(long id) {
    SysUser sysUser = sysUserMapper.selectById(id);
    if (sysUser == null) {
      sysUser = new SysUser();
      sysUser.setNickname("匿名用户");
    }
    return sysUser;
  }

  @Override
  public SysUser findUser(String account, String password) {
    LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(SysUser::getAccount, account);
    queryWrapper.eq(SysUser::getPassword, password);
    queryWrapper.select(SysUser::getAccount, SysUser::getAvatar, SysUser::getId, SysUser::getNickname);
    queryWrapper.last("limit 1");

    return sysUserMapper.selectOne(queryWrapper);
  }

  @Override
  public Result findUserBytoken(String token) {


    SysUser sysUser  = loginService.checkToken(token);
    if (sysUser == null) {
      return Result.fail(ErrorCode.TOKEN_ERROR.getCode(), ErrorCode.TOKEN_ERROR.getMsg());
    }
    LoginUserVo loginUserVo = new LoginUserVo();
    loginUserVo.setAccount(sysUser.getAccount());
    loginUserVo.setAvatar(sysUser.getAvatar());
    loginUserVo.setId(sysUser.getId());
    loginUserVo.setNickname(sysUser.getNickname());
    return Result.success(loginUserVo);
  }

  @Override
  public SysUser findUserByAccount(String account) {
    LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(SysUser::getAccount,account);
    queryWrapper.last("limit 1");
    return sysUserMapper.selectOne(queryWrapper);
  }

  @Override
  public void save(SysUser sysUser) {
    this.sysUserMapper.insert(sysUser);
  }


  @Override
  public UserVo findUserVoById(Long id) {
    SysUser sysUser = sysUserMapper.selectById(id);
    if (sysUser == null){
      sysUser = new SysUser();
      sysUser.setId(1L);
      sysUser.setAvatar("/static/img/logo.b3a48c0.png");
      sysUser.setNickname("知行合一");
    }
    UserVo userVo = new UserVo();
    userVo.setAvatar(sysUser.getAvatar());
    userVo.setNickname(sysUser.getNickname());
    userVo.setId(sysUser.getId());
    return userVo;
  }
}
